package com.yunbao.demo.permission;

import com.yunbao.demo.controller.DemoController;
import com.yunbao.ioc.annotation.Component;
import com.yunbao.web.interceptor.HandlerInterceptor;
import com.yunbao.web.servlet.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by louisyuu on 2020/3/14 下午2:42
 */

@Component("securityHandlerInterceptor")
public class SecurityHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String username = request.getParameter("username");

        HandlerMethod handlerMethod = (HandlerMethod)handler;

        boolean present = handlerMethod.getHandlerMethod().isAnnotationPresent(Security.class);

        //如果顶了@Security 那么去校验用户名是否为空以及用户名是否为admin以及manager，如果不是那么没有权限
        if(present){

            if(username==null||"".equals(username.trim())){
                response.setStatus(403);
                response.getWriter().write("Sorry you have no permission!!!");
                return false;
            }

            if(!DemoController.ADMIN.equalsIgnoreCase(username)&&!DemoController.MANAGER.equalsIgnoreCase(username)){
                response.setStatus(403);
                response.getWriter().write("Sorry you have no permission!!!");
                return false;
            }
            return true;
        }


        //如果没有顶注解那么放行

        return true;
    }
}
